<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 数据区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <!-- 展示角色的详细 -->
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['elbottom', i1 === 0 ? 'eltop' : '', 'vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <span class="el-icon-caret-right"></span>
              </el-col>
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'eltop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRoleById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <span class="el-icon-caret-right"></span>
                  </el-col>
                  <el-col :span="18">
                      <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRoleById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列表 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRole(scope.row.id)">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="editRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showEditRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 展示所有权限及赋权 -->
    <el-dialog
      title="分配权限"
      :visible.sync="roleEditDialogVisible"
      width="50%">
      <!-- 树形组件 -->
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="rightkeys"
        :props="rightsTreeProps"
        ref="treeRef"
        >
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleRightsUser()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      roleEditDialogVisible: false,
      rightsList: [],
      rightsTreeProps: {
        children: 'children',
        label: 'authName'
      },
      rightkeys: [],
      // 分配权限时的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.rolesList = res.data
    },
    // 移除角色
    async removeRoleById (role, roleId) {
      const confirmRes = await this.$confirm('此操作将移除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info('已取消删除')
      // 删除
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${roleId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
      this.$message.success('删除成功')
    },
    // 分配权限
    async showEditRightsDialog (role) {
      // 给角色赋权的时候赋roleId
      this.roleId = role.id
      this.rightkeys = []
      this.roleEditDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightsList = res.data
      // 获取三级节点
      this.getLeafNode(role, this.rightkeys)
    },
    // 递归获取三级子节点
    getLeafNode (role, arr) {
      if (!role.children) return arr.push(role.id)
      role.children.forEach(item => {
        this.getLeafNode(item, arr)
      })
    },
    // 给角色授权
    async roleRightsUser () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStrs = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStrs })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.roleEditDialogVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.eltop{
  border-top: 1px solid #eee;
}
.elbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
